# $Id: radtest.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import getpass
import optparse
import sys

from django.conf import settings

from djanet import utils
from djanet.lib import stdlib
from djanet.lib.exception import RadiusError
from djanet.tools.lib import getopts
from djanet.utils import radius

class Command(getopts.GetOptions):
   option_list = (
         optparse.make_option("-u", "--username", type = "str",
            help = "Username to authenticate using RADIUS",
            dest = "username"),
         optparse.make_option("-s", "--server", type = "str",
            help = "RADIUS server, default will use from django settings",
            dest = "server"),
         optparse.make_option("-S", "--secret", type = "str",
            help = "RADIUS secret, default will use from django settings",
            dest = "secret"),
         optparse.make_option("-p", "--password", type = "str",
            help = "Password for the username to authenticate using RADIUS",
            dest = "password"),
         ) + getopts.GetOptions.option_list

   help = """

   Program to test username/password combination to authenticate against
   either the defined server in django settings or server used with the 
   command line option

   """

   def __init__(self):
      super(Command, self).__init__()
      self._user = None
      self._radius = None


   def Authenticate(self, **options):
      retval = False
      try:
         self._radius = radius.radius(
               options.get("server"), options.get("secret"))
      except RadiusError, message:
         raise

      try:
         retval = self._radius.Authenticate(options.get("username"),
               options.get("password"))
      except RadiusError, message:
         raise

      if self._radius:
         self._radius.Close()

      return retval

   def handle(self, **options):
      self._user = options.get("username")
      password = options.get("password")
      if not self._user:
         self._user = getpass.getuser()

      if not password:
         password = getpass.getpass("Password for %s: " %self._user).strip()

      if self._user and password:
         if hasattr(settings, 'RADIUS'):
            server = settings.RADIUS['SERVER']
            secret = settings.RADIUS['SECRET']
         else:
            server = options.get("server")
            secret = options.get("secret")

         try:
            retval = self.authenticate(username = self._user,
                  password = password, server = server, secret = secret)
         except:
            sys.exit(1)
         else:
            if retval:
               print "%s successfully authenticated to %s" %(
                     self._user, server)
            else:
               print "%s cannot authenticate to %s" %(
                     self._user, server)

